package com.guifan.controller.advice;

import com.guifan.controller.exception.APIException;
import com.guifan.inter.enums.ResultCode;
import com.guifan.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author God.Jhon.Black
 * @date 2023-01-17
 */
@RestControllerAdvice
@Slf4j
public class ControllerExceptionAdvice {

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResultVo MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return new ResultVo(ResultCode.VALIDATE_ERROR, objectError.getDefaultMessage());
    }

    @ExceptionHandler(APIException.class)
    public ResultVo APIExceptionHandler(APIException e) {
        log.error("========my exception send:=======" + e.getMsg());
        return new ResultVo(e.getCode(), e.getMsg(), e.getMessage());
    }
}
